import base64
import hmac
import urllib

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
from myapp.myser import UserSer
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量,密钥
from mydjango.settings import BASE_DIR,SECRET_TOKEN


#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入序列化对象
from myapp.myser import UserSer

import redis

#   七牛云上传模块
from qiniu import Auth
# token模块
import jwt

from django.utils.decorators import method_decorator

host = '127.0.0.1'
port = 6379

r = redis.Redis(host=host,port=port)

# 装饰器
def my_decorator(func):
    def wrapper(request,*args,**kwargs):
        print('这个装饰器被调用了'+request.path)
        # 判断逻辑
        uid = request.GET.get('uid')
        token = request.GET.get('token',None)

        token_decode = jwt.decode(token, SECRET_TOKEN)

        if str(token_decode['uid']) != uid:
            return JsonResponse({'error': "请求错误"})
        return func(request,*args,**kwargs)
    return wrapper


# 用户信息类
class UserInfo(APIView):
    # @method_decorator(my_decorator)
    def get(self,request):
        uid = request.GET.get('uid')

        user = User.objects.filter(id=uid).first()

        ser = UserSer(user)

        return Response(ser.data)


# 七牛云接口
class QiuNiu(APIView):

    def get(self,request):
        #定义密钥
        q = Auth('mARrCH5xfDiTTrkDVYo0wS40bOAy00zAtLZvbyfA','uHl5vArUQDy-dvn30AR5Rhil-9I2rXXXUXGTWvS0')

        token = q.upload_token('mdmsh')
        res = {}
        res['token'] = token
        return Response(res)

    def post(self,request):
        url = request.data.get('url')
        uid = request.GET.get('uid')
        #查询需要修改的img地址
        user = User.objects.filter(id=uid).first()
        # 保存并修改
        user.img = url
        user.save()

        return Response({'message':'保存成功'})
def ChangePassword(request):
    uid = request.GET.get('uid')
    password = request.GET.get('password')

    user = User.objects.filter(id=uid).first()

    user.password = make_password(password)
    user.save()
    res = {}
    res['code'] = 200
    res['message'] = '修改成功'

    return JsonResponse(res)



class UploadFile(View):
    def get(self,request):
        uid = request.GET.get('uid')

        user = User.objects.filter(id=uid).first()

        res = {}
        res['code'] = 200
        res['imgurl'] = user.img

        return JsonResponse(res)

    def post(self,request):
        img = request.FILES.get('file')

        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,"",img.name),'wb')
        # 写入服务器
        for chunk in img.chunks():
            f.write(chunk)
        f.close()
        index = img.name.rfind('.')
        imglist = ["jpg",'png']
        if img.name[index+1:] in imglist:
            im = Image.open('./static/upload/'+img.name)

            draw = ImageDraw.Draw(im)
            draw.text((0, 0), 'mdshop', fill=(76, 234, 124, 180))

            # 保存
            im.save('./static/upload/'+img.name)

        return HttpResponse(json.dumps({'filename':img.name},ensure_ascii=False),content_type='application/json')


class DingDingLogin(APIView):

    def get(self,request):
        code = request.GET.get('code')

        t = time.time()
        appSecret = "eMd7zuSSTfsXcbBg2SSBIODnZlDSwv8kWq_RStPudmEDTyEesp-U3UJoLzPOAnmB"
        timestamp = str(int(round(t * 1000)))
        signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=hashlib.sha256).digest())
        request_url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=dingoasyyehyz5u1fzgmcv&timestamp="+timestamp+"&signature="+urllib.parse.quote(signature.decode('utf-8'))
        headers = {'Content-Type':'application/json'}
        res = requests.post(url=request_url,data=json.dumps({'tmp_auth_code':code}),headers=headers)
        data = res.json()['user_info']['nick']

        user = User.objects.filter(username=str(data)).first()

        if user:
            return redirect('http://127.0.0.1:8080?username=' + user.username + "&uid=" + str(user.id))
        else:
            u = User(username=str(data), password="", img='1', type='0')
            u.save()
            us = User.objects.filter(username=str(data)).first()
            return redirect('http://127.0.0.1:8080?username=' + us.username + "&uid=" + str(us.id))



class WeiboLogin(APIView):

    def get(self,request):
        code = request.GET.get('code')
        request_url = "https://api.weibo.com/oauth2/access_token?client_id=2644557550&client_secret=83c557f2b0cf94bfd9a943b9027b826b" \
                      "&frant_type=authorization_code&redirect_uri=http://127.0.0.1:8000/weibo_back/&code="+code

        res = requests.post(request_url)

        # res = requests.post(request_url,data={
        #     "client_id":2644557550,
        #     'client_secret':"83c557f2b0cf94bfd9a943b9027b826b",
        #     'frant_type':"authorization_code",
        #     'code':code,
        #     "redirect_uri":"http://127.0.0.1:8000/weibo_back/"
        # })

        # 获取微博的真实昵称
        result = requests.get('https://api.weibo.com/2/users/show.json',params={
            'access_token':res.json()['access_token'],'uid':res.json()['uid']
        })
        name = result.json()['name']

        user = User.objects.filter(username=str(name)).first()

        if user:
            return redirect('http://127.0.0.1:8080?username='+user.username+"&uid="+str(user.id))
        else:
            u = User(username=str(name),password="",img='1',type='0')
            u.save()
            us = User.objects.filter(username=str(name)).first()
            return redirect('http://127.0.0.1:8080?username='+us.username+"&uid="+str(us.id))


# 登录
class Login(APIView):

    def get(self,request):
        username = request.GET.get('username')
        password = request.GET.get('password')

        user = User.objects.filter(username=username,password=make_password(password)).first()

        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['uid'] = user.id
            res['username'] = user.username
            token_jwt = jwt.encode({'uid':user.id},SECRET_TOKEN,algorithm='HS256')
            res['token'] = token_jwt

            return Response(res)
        else:
            res = {}
            res['code'] = 400
            res['message'] = '用户名或密码错误'
            return Response(res)



# 定义验证码类
class MyCode(View):
    # 定义图片颜色
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)

        return (R,G,B)
    # 验证码视图
    def get(self,request):
        # 定义画布
        img_size = (120,50)
        # 定义画布对象
        image = Image.new('RGB',img_size,'white')
        # 画笔对象
        draw = ImageDraw.Draw(image,'RGB')
        # 定义随机字符串
        souce = '男方如果发放让关闭'
        # 验证码容器
        code = ''
        myfont = ImageFont.truetype(font='ttf/msyh.ttc',size=10)
        for i in range(4):
            # 获取随机颜色
            text_color = self.get_random_color()
            # 获取随机串长度
            tmp_num = random.randrange(len(souce))
            # 获取字符集
            random_str = souce[tmp_num]
            # 添加到容器中
            code += random_str
            draw.text((10+30*i,20),random_str,text_color,font=myfont)
        # 建立缓冲区
        buf = io.BytesIO()
        image.save(buf,'png')
        # 存储验证码
        r.set('code',code)
        request.session['code'] = code
        return HttpResponse(buf.getvalue(),'image/png')

# MD5加密方法
def make_password(mypassword):

    # 生成MD5对象
    md5 = hashlib.md5()
    # 将密码转转为字符串
    sing_str = str(mypassword)
    # 将密码转为字节码
    sing_str = sing_str.encode(encoding='utf-8')
    # 加密
    md5.update(sing_str)
    # 生成秘钥串
    server_str = md5.hexdigest()

    return server_str



class RegisterView(APIView):

    def get(self,request):
        username = request.GET.get('username','null')
        password = request.GET.get('password','null')
        code = request.GET.get('code','null')

        codestr = r.get('code').decode('utf-8')
        # session保存的code
        # session_code = request.session.get('code')

        user = User.objects.filter(username=username).first()
        if user:
            res = {}
            res['code'] = 400
            res['message'] = '该用户已经注册'
            return Response(res)


        if code != codestr:
            res = {}
            res['code'] = 405
            res['message'] = '验证码错误'
            return Response(res)

        u = User(username=username,password=make_password(password),type=0,img='?')
        u.save()
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)




